package com.probox.common.entity.service.product.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.probox.common.core.constant.CachePrefix;
import com.probox.common.core.enums.CommentTypeEnum;
import com.probox.common.core.enums.DataStatus;
import com.probox.common.core.enums.PlatformSettingEnum;
import com.probox.common.core.enums.ProductOptType;
import com.probox.common.core.exception.BaseException;
import com.probox.common.core.exception.PlatformException;
import com.probox.common.core.utils.DateUtils;
import com.probox.common.core.utils.SecurityUtils;
import com.probox.common.entity.domain.product.ProductComment;
import com.probox.common.entity.domain.product.vo.ProductCommentQuery;
import com.probox.common.entity.domain.product.vo.ProductCommentVo;
import com.probox.common.entity.mapper.product.ProductCommentMapper;
import com.probox.common.entity.service.customer.ICustomerInfoService;
import com.probox.common.entity.service.platfom.IPlatformGeneralsettingsService;
import com.probox.common.entity.service.product.IProductCommentService;
import com.probox.common.redis.service.RedisService;
import com.probox.platform.api.domain.PlatformGeneralsettingsVo;
import com.probox.product.api.domain.ProductCommentApiVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 商品评论信息Service业务层处理
 *
 * @date 2021-06-07
 */
@Service
@Transactional
public class ProductCommentServiceImpl extends ServiceImpl<ProductCommentMapper, ProductComment> implements IProductCommentService {
    @Autowired
    private ProductCommentMapper productCommentMapper;

    @Autowired
    private ICustomerInfoService iCustomerInfoService;

    @Autowired
    private RedisService redisService;


    @Autowired
    private IPlatformGeneralsettingsService platformGeneralsettingsService;

    private static final Logger logger = LoggerFactory.getLogger(ProductCommentServiceImpl.class);


    /**
     * 查询商品评论信息
     *
     * @param commentUid 商品评论信息ID
     * @return 商品评论信息
     */
    @Override
    public ProductComment selectProductCommentById(Long commentUid) {
        return this.getById(commentUid);
    }

    /**
     * 查询商品评论信息列表
     *
     * @param productCommentQuery 商品评论信息
     * @return 商品评论信息
     */
    @Override
    public List<ProductCommentVo> queryList(ProductCommentQuery productCommentQuery) {
        if (ObjectUtil.isEmpty(productCommentQuery.getPlatformUid())) {
            Long platformId = SecurityUtils.getPlatformId();
            if (platformId == null) {
                throw new BaseException("当前账号异常");
            }
            productCommentQuery.setPlatformUid(platformId);
        } else {
            PlatformGeneralsettingsVo vo = platformGeneralsettingsService.get(productCommentQuery.getPlatformUid());
            if (ObjectUtil.isNotEmpty(vo)) {
                if (PlatformSettingEnum.show.getKey().equals(vo.getIsGoodsComment())) {
                    if (PlatformSettingEnum.show.getKey().equals(Convert.toStr(vo.getCommentServiceMap().get("default")))) {
                        productCommentQuery.setSettingsService(Convert.toInt(vo.getCommentServiceMap().get("rate")) * 10);
                    }
                    if (PlatformSettingEnum.show.getKey().equals(Convert.toStr(vo.getCommentProductMap().get("default")))) {
                        productCommentQuery.setSettingspProduct(Convert.toInt(vo.getCommentProductMap().get("rate")) * 10);
                    }
                    if (PlatformSettingEnum.show.getKey().equals(Convert.toStr(vo.getCommentLogisticsMap().get("default")))) {
                        productCommentQuery.setSettingsLogistics(Convert.toInt(vo.getCommentLogisticsMap().get("rate")) * 10);
                    }
                }
            }
            productCommentQuery.setIsShow("1");
        }
        return productCommentMapper.List(productCommentQuery);
    }

    /**
     * api 获取总条数
     *
     * @param productCommentQuery
     * @return
     */
    @Override
    public Integer queryListCount(ProductCommentQuery productCommentQuery) {
        if (ObjectUtil.isEmpty(productCommentQuery.getPlatformUid())) {
            Long platformId = SecurityUtils.getPlatformId();
            if (platformId == null) {
                throw new BaseException("当前账号异常");
            }
            productCommentQuery.setPlatformUid(platformId);
        }
        List<ProductCommentVo> list = productCommentMapper.List(productCommentQuery);
        if (ObjectUtil.isEmpty(list)) return 0;
        return list.size();
    }

    /**
     * 新增商品评论信息
     *
     * @param volist 商品评论信息
     * @return 结果
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public boolean insertProductComment(List<ProductCommentApiVo> volist) {
        AtomicInteger index = new AtomicInteger();
        if (ObjectUtil.isEmpty(volist)) throw new PlatformException("商品评论出错,请重新评论");
        HashMap map = iCustomerInfoService.getCustomerInfoDetail(volist.get(0).getMemberUid());
        volist.forEach(vo -> {
            ProductComment comment = new ProductComment();
            BeanUtils.copyProperties(vo, comment);
            comment.setMemberName(map.get("customerName").toString());
            if (ObjectUtil.isNotEmpty(map.get("accountNickName"))) {
                comment.setMemberNickName(map.get("accountNickName").toString());
            }
            if (ObjectUtil.isNotEmpty(map.get("headImage"))) {
                comment.setMemberHeadUrl(map.get("headImage").toString());
            }
            logger.debug("==========商品评论时间:"+vo.getCommentTime()+"===========================");
            comment.setCommentTime(DateUtils.parseDate(vo.getCommentTime()));
            comment.setDataStatus(DataStatus.valid.getKey());
            boolean save = this.save(comment);
            if (save) index.getAndIncrement();

        });
        if (index.get() == volist.size()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 修改商品评论信息
     *
     * @param productComment 商品评论信息
     * @return 结果
     */
    @Override
    public boolean updateProductComment(ProductComment productComment) {
        productComment.setMerchantTime(DateUtil.date());
        productComment.setMerchantName(SecurityUtils.getUsername());
        redisService.deleteObject(CachePrefix.API_PRODUCT_DETAIL + productComment.getProductUid());
        return this.updateById(productComment);
    }

    @Override
    public boolean updateComment(ProductComment productComment){
        redisService.deleteObject(CachePrefix.API_PRODUCT_DETAIL + productComment.getProductUid());

        return this.updateById(productComment);
    }

    /**
     * 批量删除商品评论信息
     *
     * @param commentUids 需要删除的商品评论信息ID
     * @return 结果
     */
    @Override
    public boolean deleteProductCommentByIds(Long[] commentUids) {
        return this.removeByIds(Arrays.asList(commentUids));
    }

    /**
     * 获得商品评论的筛选标签以及每种标签的数量
     *
     * @param productUid
     * @return
     */
    @Override
    public List<HashMap> getCommentNum(Long productUid) {
        List<HashMap> list = new ArrayList<>();
        QueryWrapper<ProductComment> queryAll = new QueryWrapper<>();
        queryAll.eq("DATA_status", DataStatus.valid.getKey());
        queryAll.eq("PRODUCT_UID", productUid);
        list.add(setMap(CommentTypeEnum.all.getKey(), CommentTypeEnum.all.getValue(), productCommentMapper.selectCount(queryAll)));
        QueryWrapper<ProductComment> queryTime = new QueryWrapper<>();
        DateTime date = DateUtil.date();
        Date date1 = DateUtils.addDay(date, -7);
        queryTime.eq("DATA_status", DataStatus.valid.getKey());
        queryTime.eq("PRODUCT_UID", productUid);
        queryTime.le("COMMENT_TIME", DateUtils.getTime());
        queryTime.ge("COMMENT_TIME", DateUtils.formateToday(date1) + " 00:00:00");
        queryTime.eq("IS_SHOW","1");
        list.add(setMap(CommentTypeEnum.newTime.getKey(), CommentTypeEnum.newTime.getValue(), productCommentMapper.selectCount(queryTime)));
        QueryWrapper<ProductComment> queryImg = new QueryWrapper<>();
        queryImg.eq("DATA_status", DataStatus.valid.getKey());
        queryImg.eq("PRODUCT_UID", productUid);
        queryImg.isNotNull("IMAGES_URL");
        queryImg.eq("IS_SHOW","1");
        list.add(setMap(CommentTypeEnum.img.getKey(), CommentTypeEnum.img.getValue(), productCommentMapper.selectCount(queryImg)));
        QueryWrapper<ProductComment> queryProduct = new QueryWrapper<>();
        queryProduct.eq("DATA_status", DataStatus.valid.getKey());
        queryProduct.eq("PRODUCT_UID", productUid);
        queryProduct.eq("PRODUCT_SCORE", "50");
        queryProduct.eq("IS_SHOW","1");
        list.add(setMap(CommentTypeEnum.productScore.getKey(), CommentTypeEnum.productScore.getValue(), productCommentMapper.selectCount(queryProduct)));
        QueryWrapper<ProductComment> queryLogistic = new QueryWrapper<>();
        queryLogistic.eq("DATA_status", DataStatus.valid.getKey());
        queryLogistic.eq("PRODUCT_UID", productUid);
        queryLogistic.eq("LOGISTICS_SCORE", "50");
        queryLogistic.eq("IS_SHOW","1");
        list.add(setMap(CommentTypeEnum.logisticScore.getKey(), CommentTypeEnum.logisticScore.getValue(), productCommentMapper.selectCount(queryLogistic)));
        QueryWrapper<ProductComment> queryService = new QueryWrapper<>();
        queryService.eq("DATA_status", DataStatus.valid.getKey());
        queryService.eq("PRODUCT_UID", productUid);
        queryService.eq("SERVICE_SCORE", "50");
        queryService.eq("IS_SHOW","1");
        list.add(setMap(CommentTypeEnum.serviceScore.getKey(), CommentTypeEnum.serviceScore.getValue(), productCommentMapper.selectCount(queryService)));
        return list;
    }

    private HashMap setMap(String type, String name, Integer number) {
        HashMap map = new HashMap();
        map.put("commentTags", type);
        map.put("tagName", name);
        map.put("number", number);
        return map;
    }

}
